package com.yeskery.nut.web.demo.runner;

import com.yeskery.nut.annotation.bean.Autowired;
import com.yeskery.nut.annotation.bean.Component;
import com.yeskery.nut.annotation.environment.Value;
import com.yeskery.nut.core.CommandLineRunner;
import com.yeskery.nut.core.InputStreamResource;
import com.yeskery.nut.extend.jdbc.JdbcTemplate;
import com.yeskery.nut.extend.redis.JedisExecutor;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.logging.Logger;

/**
 * 初始化数据信息
 * @author Yeskery
 * 2023/7/27
 */
@Component
public class DataInitializeRunner implements CommandLineRunner {

    /** 日志对象 */
    private static final Logger logger = Logger.getLogger(DataInitializeRunner.class.getName());

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Value("classpath:init_table.sql")
    private InputStreamResource initTableResource;

    @Value("classpath:init_data.sql")
    private InputStreamResource initDataResource;

    //@Autowired
    //private JedisExecutor jedisExecutor;

    @Override
    public void run(String[] args) throws Exception {
        // 初始化表结构
        logger.info("初始化表结构开始");
        BufferedReader br = new BufferedReader(new InputStreamReader(initTableResource.getInputStream()));
        jdbcTemplate.batchExecute(br.lines().toArray(String[]::new));

        logger.info("初始化表结构结束");

        // 初始化表数据
        logger.info("初始化表数据开始");
        br = new BufferedReader(new InputStreamReader(initDataResource.getInputStream()));
        jdbcTemplate.batchExecute(br.lines().toArray(String[]::new));
        logger.info("初始化表数据结束");

        // 清空redis数据库
        /*logger.info("清空redis数据库开始");
        jedisExecutor.execute(Jedis::flushDB);
        logger.info("清空redis数据库结束");*/
    }
}
